package com.lk.api.tools;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

/**
 * Created by lk on 2014/12/31.
 */
public class HttpGetImage {
    private static final int MSG_SUCCESS = 0;//获取图片成功的标识
    private static final int MSG_FAILURE = 1;//获取图片失败的标识
    private Thread mThread;
    private ImageView mImageView;
    String mUriPath;
    Message mMessage;
    public  HttpGetImage(String UriPath, ImageView imageView) {
        mUriPath = UriPath;
        mImageView=imageView;
        if (mThread == null) {
            mThread = new Thread(runnable);
            mThread.start();//线程启动
        } else {
        }
    }



    private Handler mHandler = new Handler() {
        //此方法在ui线程运行
        public void handleMessage(Message msg) {
            mMessage=msg;
            if (msg.what == MSG_SUCCESS) {
                //imageview显示从网络获取到的logo
                mImageView.setImageBitmap((Bitmap) msg.obj);
            } else if (msg.what == MSG_FAILURE) {
            }


        }
    };


    Runnable runnable = new Runnable() {

        @Override
        public void run() {//run()在新的线程中运行
            HttpClient hc = new DefaultHttpClient();
            HttpGet hg = new HttpGet(mUriPath);//获取csdn的logo
            final Bitmap bm;
            try {
                HttpResponse hr = hc.execute(hg);
                bm = BitmapFactory.decodeStream(hr.getEntity().getContent());

            } catch (Exception e) {
                mHandler.obtainMessage(MSG_FAILURE).sendToTarget();//获取图片失败
                return;
            }
            mHandler.obtainMessage(MSG_SUCCESS, bm).sendToTarget();//获取图片成功，向ui线程发送MSG_SUCCESS标识和bitmap对象

        }
    };
}
